package cn.team11.smarteye.fragment;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import net.lucode.hackware.magicindicator.buildins.UIUtil;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.team11.sds.dayi.R;
import cn.team11.smarteye.activity.CateyeDeviceDetailActivity;
import cn.team11.smarteye.activity.ImageDetailActivity;
import cn.team11.smarteye.activity.callback.AlarmMessageCallback;
import cn.team11.smarteye.activity.callback.AlarmMessageResultCallback;
import cn.team11.smarteye.adapter.CommonAdapter;
import cn.team11.smarteye.adapter.CommonViewHolder;
import cn.team11.smarteye.base.BaseDialog;
import cn.team11.smarteye.base.BaseFragment;
import cn.team11.smarteye.base.BasePresenter;
import cn.team11.smarteye.bean.AlarmMsgInfoBean;
import cn.team11.smarteye.misc.SConstants;
import cn.team11.smarteye.module.DownloadInfo;
import cn.team11.smarteye.module.DownloadManager;
import cn.team11.smarteye.module.DownloadObserver;
import cn.team11.smarteye.module.MyDaoManager;
import cn.team11.smarteye.service.CatEyeService;
import cn.team11.smarteye.utils.AppLogger;
import cn.team11.smarteye.utils.ListUtils;
import cn.team11.smarteye.utils.TimeUtils;
import cn.team11.smarteye.utils.ToastUtil;
import cn.team11.smarteye.widget.AlarmCalendarPopupView;
import cn.team11.smarteye.widget.CustomLoadingDialog;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Murphy on 2017/11/1.
 */

public class AlarmMessageFragment extends BaseFragment implements AlarmCalendarPopupView.OnCalendarListener, AlarmMessageResultCallback, CommonAdapter.OnItemClickListener {

    @BindView(R.id.alarm_msg_listview)
    RecyclerView mAlarmMsgListRView;
    @BindView(R.id.no_alarm_msg_img)
    ImageView mNoMsgImg;
    @BindView(R.id.choose_time_bt_in_alert)
    TextView mChooseTime;
    @BindView(R.id.edit_mode_button_layout)
    LinearLayout mEditModeBtLayout;
    @BindView(R.id.refresh_alarms)
    SwipeRefreshLayout mRefreshLayout;


    private AlarmMessageCallback mCallback;

    private AlarmMessageListAdapter mAdapter;
    private Disposable mTimeoutDisposables;

    private int badgeCount = 0;

    //private List<CustomMessageBean> mMsgList = new ArrayList<>();
    private List<AlarmMsgInfoBean> mMsgList = new CopyOnWriteArrayList<>();
    private String seletedDate;

    private boolean isEditMode = false;//默认为非编辑模式

    public static AlarmMessageFragment newInstance(Bundle bundle) {
        AlarmMessageFragment fragment = new AlarmMessageFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_alert_message, container, false);
        ButterKnife.bind(this, view);
        init();
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initSwipeRefresh();
        AppLogger.i("AlarmMessageFragment onViewCreated");
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void init() {


        //注册自己，用于接收Activity的消息
        ((CateyeDeviceDetailActivity) getActivity()).registerAlarmMsgResultCallback(this);
        mCallback = (AlarmMessageCallback) getActivity();
        seletedDate = TimeUtils.dateToString(new Date());


        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        mAlarmMsgListRView.setLayoutManager(linearLayoutManager);
        //mAlarmMsgListRView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
        //mAdapter = new AlarmMessageListAdapter(getActivity(), R.layout.cateye_alarm_msg_list_item, mAlarmMsgList);
        mAdapter = new AlarmMessageListAdapter(getActivity(), R.layout.cateye_alarm_msg_list_item, mMsgList);
        mAlarmMsgListRView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(this);

        mChooseTime.setText(seletedDate.substring(5, 10));
    }

    private void initSwipeRefresh() {
        getAlarms();
        mRefreshLayout.setColorSchemeResources(R.color.color_main_green);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //presenter更新数据
                createTimer();
                getAlarms();
            }
        });
    }


    private void getAlarms() {
        if (mCallback != null) {
            mMsgList.clear();
            final long starttime = TimeUtils.stringToTimestamp(seletedDate.substring(0, 10) + " 00:00:00");
            mCallback.getLocalAlarmMsg(starttime, starttime + 86400000)
                    .delay(1, TimeUnit.SECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<AlarmMsgInfoBean>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {

                        }

                        @Override
                        public void onNext(@NonNull AlarmMsgInfoBean alarmMsgInfoBean) {
                            mMsgList.add(alarmMsgInfoBean);
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {

                        }

                        @Override
                        public void onComplete() {
                            if (mTimeoutDisposables != null && !mTimeoutDisposables.isDisposed()){
                                mTimeoutDisposables.dispose();
                                mRefreshLayout.setRefreshing(false);
                            }
                            if (ListUtils.isEmpty(mMsgList)) {
                                mNoMsgImg.setVisibility(View.VISIBLE);
                            } else {
                                mNoMsgImg.setVisibility(View.INVISIBLE);
                                mAdapter.notifyDataSetChanged();
                                mRefreshLayout.setRefreshing(false);
                            }
                        }
                    });
        }
    }


    @OnClick({R.id.choose_time_bt_in_alert, R.id.mark_read_bt, R.id.e_delete_bt})
    public void onChooseTime(View view) {
        switch (view.getId()) {
            case R.id.choose_time_bt_in_alert:
                AlarmCalendarPopupView calendar = new AlarmCalendarPopupView(getActivity());
                calendar.setOnCalendarListener(this);
                calendar.showAsDropDown(view, 0, 27);
                break;
            case R.id.mark_read_bt:
                Observable.fromIterable(mMsgList)
                        .filter(new Predicate<AlarmMsgInfoBean>() {
                            @Override
                            public boolean test(@NonNull AlarmMsgInfoBean alarmMsgInfoBean) throws Exception {
                                return alarmMsgInfoBean.isSelected();
                            }
                        })
                        .observeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<AlarmMsgInfoBean>() {
                            @Override
                            public void onSubscribe(@NonNull Disposable d) {

                            }

                            @Override
                            public void onNext(@NonNull AlarmMsgInfoBean alarmMsgInfoBean) {
                                alarmMsgInfoBean.setMarkAsRead(true);
                                MyDaoManager.getInstance(getActivity()).updateAlarmMsgReadableStatus(alarmMsgInfoBean.getAid(), true);
                            }

                            @Override
                            public void onError(@NonNull Throwable e) {

                            }

                            @Override
                            public void onComplete() {
                                leaveEditMode();
                            }
                        });
                break;
            case R.id.e_delete_bt:
                if (CatEyeService.icvss != null) {
                    Bundle b = new Bundle();
                    b.putString("title", getString(R.string.delete_alarm_msg));
                    b.putString("content", getString(R.string.delete_alarm_msg_tips));
                    final TextDialogFragment restartDialog = TextDialogFragment.newInstance(b);
                    restartDialog.show(getFragmentManager(), "delete_msg");
                    restartDialog.setOnBtClickListener(new BaseDialog.OnBtClickListener() {
                        @Override
                        public void onConfirmClick() {

                            Observable.fromIterable(mMsgList)
                                    .filter(new Predicate<AlarmMsgInfoBean>() {
                                        @Override
                                        public boolean test(@NonNull AlarmMsgInfoBean alarmMsgInfoBean) throws Exception {
                                            return alarmMsgInfoBean.isSelected();
                                        }
                                    })
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(new Observer<AlarmMsgInfoBean>() {
                                        @Override
                                        public void onSubscribe(@NonNull Disposable d) {

                                        }

                                        @Override
                                        public void onNext(@NonNull AlarmMsgInfoBean alarmMsgInfoBean) {
                                            mMsgList.remove(alarmMsgInfoBean);
                                            MyDaoManager.getInstance(getActivity()).deleteAlarmMsg(alarmMsgInfoBean);
                                            mCallback.deleteAlarmMsg(alarmMsgInfoBean.getAid(), 0);
                                        }

                                        @Override
                                        public void onError(@NonNull Throwable e) {

                                        }

                                        @Override
                                        public void onComplete() {
                                            leaveEditMode();
                                            showNoMsgTips();
                                        }
                                    });
                            restartDialog.dismiss();
                        }

                        @Override
                        public void onCancelClick() {
                            restartDialog.dismiss();
                        }
                    });
                }
                break;
        }
    }

    @Override
    public void onSelectedDateString(String dateStr) {
        mMsgList.clear();
        seletedDate = dateStr;
        mChooseTime.setText(dateStr.substring(5, 10));
        if (mCallback != null) {
            final long starttime = TimeUtils.stringToTimestamp(dateStr + " 00:00:00");
            mCallback.getLocalAlarmMsg(starttime, starttime + 86400000)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<AlarmMsgInfoBean>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {

                        }

                        @Override
                        public void onNext(@NonNull AlarmMsgInfoBean alarmMsgInfoBean) {
                            mMsgList.add(alarmMsgInfoBean);
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {

                        }

                        @Override
                        public void onComplete() {
                            showNoMsgTips();
                            mAdapter.notifyDataSetChanged();
                        }
                    });
        }
    }

    @Override
    public void setPresenter(BasePresenter presenter) {

    }


    /**
     * 进入编辑状态
     */
    private void enterEditMode() {
        if (mCallback != null) {
            isEditMode = true;
            mCallback.setCanScroll(false);
            mEditModeBtLayout.setVisibility(View.VISIBLE);
            mCallback.setCustomTitle(getResources().getString(R.string.cancel), 1);
            mCallback.setCustomTitle(getResources().getString(R.string.select_all), -1);
            mCallback.setCustomTitleImage(null, -1);
            mCallback.setTabVisiable(View.GONE);
            mAdapter.setEditMode(isEditMode);
        }
    }

    /**
     * 离开编辑状态
     */
    private void leaveEditMode() {
        if (mCallback != null) {
            isEditMode = false;
            mCallback.setCanScroll(true);
            showNoMsgTips();
            mEditModeBtLayout.setVisibility(View.INVISIBLE);
            mCallback.setCustomTitle(getResources().getString(R.string.edit_txt), 1);
            mCallback.setCustomTitle("", -1);
            Drawable iconDrawable = ContextCompat.getDrawable(getActivity(), R.drawable.nav_icon_back);
            iconDrawable.setBounds(0, 0, UIUtil.dip2px(getActivity(), 20), UIUtil.dip2px(getActivity(), 20));
            mCallback.setCustomTitleImage(iconDrawable, -1);
            mCallback.setTabVisiable(View.VISIBLE);
            mAdapter.setEditMode(isEditMode);
        }
    }

    private void showNoMsgTips(){
        if (ListUtils.isEmpty(mMsgList)){
            mNoMsgImg.setVisibility(View.VISIBLE);
        } else {
            mNoMsgImg.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void onRightButtonClick(View view) {
        if (!isEditMode) {
            enterEditMode();
        } else {
            leaveEditMode();
        }
    }

    @Override
    public void onLeftButtonOnClick(View view) {
        //全选操作
        if (!((TextView) view).getText().equals("")) {
            for (int i = 0; i < mMsgList.size(); i++) {
                mMsgList.get(i).setSelected(true);
            }
            mAdapter.notifyDataSetChanged();
        } else {
            getActivity().finish();
        }

    }

    @Override
    public void onItemClick(View view, int position) {
        if (isEditMode) {
            CommonViewHolder holder = (CommonViewHolder) mAlarmMsgListRView.getChildViewHolder(view);
            boolean isSel = mMsgList.get(position).isSelected();
            if (isSel) {
                mMsgList.get(position).setSelected(false);
            } else {
                mMsgList.get(position).setSelected(true);
            }
            if (mMsgList.get(position).isSelected()) {//如果被选中
                holder.getView(R.id.check_status_bt).setSelected(true);
                holder.getConvertView().setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.color_item_selected));
            } else {
                holder.getView(R.id.check_status_bt).setSelected(false);
                holder.getConvertView().setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.color_white));
            }
        } else {//跳转
            //标记为已读,并更新数据库
            mMsgList.get(position).setMarkAsRead(true);
            String fid = mMsgList.get(position).getPvid().get(0);//默认取第一个
            String bid = mMsgList.get(position).getBid();
            Intent intent = new Intent(getActivity(), ImageDetailActivity.class);
            intent.putExtra(SConstants.BID, bid);
            intent.putExtra(SConstants.FIDS, fid);
            intent.putExtra(SConstants.IMAGE_TYPE, SConstants.ALARM_IMAGE);
            intent.putExtra(SConstants.CREATE_TIME, mMsgList.get(position).getTime());
            getActivity().startActivity(intent);
        }
    }

    @Override
    public void onNewAlarmMsgReceived(AlarmMsgInfoBean alarm) {
        if (alarm != null) {
            mMsgList.add(alarm);
            badgeCount++;
            mAdapter.notifyDataSetChanged();
            showNoMsgTips();
            if (mCallback != null) {
                mCallback.addBadge(1, badgeCount);
            }
        }
    }


    private void downloadAlarmMsgFile(AlarmMsgInfoBean alarm){
        String fid = alarm.getFid().get(0);//默认取第一个
        String bid = alarm.getBid();
        final String filename = alarm.getPath() + File.separator + fid;
        //下载文件并打开
        if (CatEyeService.icvss != null) {
            final CustomLoadingDialog loadingDialog = new CustomLoadingDialog(getActivity(), R.style.common_dialog_theme);
            loadingDialog.show();
            loadingDialog.setLoadingTips(getActivity().getResources().getString(R.string.is_downloading));
            String url = CatEyeService.icvss.equesGetAlarmfileUrl(fid, bid).toString();
            DownloadManager.getInstance().download(filename, url, new DownloadObserver() {
                @Override
                public void onNext(DownloadInfo downloadInfo) {
                    super.onNext(downloadInfo);
                    //可以在这里更新进度.

                }

                @Override
                public void onComplete() {
                    //下载完成
                    loadingDialog.dismiss();
                    //打开该文件
                    Intent intent = new Intent();
                    //if (downloadInfo != null){

                    //}
                    File file = new File(filename);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setAction(Intent.ACTION_VIEW);
                    String type = SConstants.getMIMEType(file);
                    intent.setDataAndType(Uri.fromFile(file), type);
                    try {
                        getActivity().startActivity(intent);
                    } catch (ActivityNotFoundException e) {
                        ToastUtil.showNegativeToast(getString(R.string.not_supported_format));
                    }
                }
            });
        }
    }

    @Override
    public void resetBadgeCount() {
        badgeCount = 0;
    }

    private void createTimer() {
        mTimeoutDisposables = Observable.interval(0, 1, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Long>() {
            @Override
            public void accept(Long aLong) throws Exception {
                if (aLong == 5) {//timeout
                    //显示添加设备提示View
                    mRefreshLayout.setRefreshing(false);
                    mTimeoutDisposables.dispose();
                }
            }
        });
    }

    /**
     * Created by Yang on 2017/11/4.
     */

    public class AlarmMessageListAdapter extends CommonAdapter<AlarmMsgInfoBean>{

        private boolean isEditable = false;

        public AlarmMessageListAdapter(Context mContext, int mLayoutId, List<AlarmMsgInfoBean> mDatas) {
            super(mContext, mLayoutId, mDatas);
        }

        @Override
        public void convert(CommonViewHolder holder, AlarmMsgInfoBean alarmMessagBean) {
            holder.setText(R.id.alarm_msg_create_device, mCallback.getNickName());
            holder.setText(R.id.alarm_msg_create_time, TimeUtils.timeMinute(alarmMessagBean.getTime()));
            ImageView thumbView = holder.getView(R.id.msg_create_img_thumb);
            ImageView msgReadStatus = holder.getView(R.id.msg_read_status);
            ImageView typeView = holder.getView(R.id.msg_pic_type);
            ImageView checkable = holder.getView(R.id.check_status_bt);

            if (isEditable){
                checkable.setVisibility(View.VISIBLE);
                if (alarmMessagBean.isSelected()){
                    checkable.setSelected(true);
                    holder.getConvertView().setBackgroundColor(ContextCompat.getColor(mContext, R.color.color_item_selected));
                }
            } else {
                checkable.setVisibility(View.INVISIBLE);
                holder.getConvertView().setBackgroundColor(ContextCompat.getColor(mContext, R.color.color_white));
                alarmMessagBean.setSelected(false);
                checkable.setSelected(false);
            }


            if (alarmMessagBean.isMarkAsRead()){
                msgReadStatus.setSelected(true);
            } else {
                msgReadStatus.setSelected(false);
            }

            //加载一张缩略图
            if (CatEyeService.icvss != null){
                String imgUrl = CatEyeService.icvss.equesGetThumbUrl(alarmMessagBean.getPvid().get(0), alarmMessagBean.getBid()).toString();
                Glide.with(mContext).load(imgUrl).override(UIUtil.dip2px(mContext, 120), UIUtil.dip2px(mContext, 100)).into(thumbView);
            }

            switch (alarmMessagBean.getType()){
                case 3://单张图片
                    typeView.setImageResource(R.drawable.icon_single_pic_type);
                    break;
                case 4://多张图片
                    typeView.setImageResource(R.drawable.icon_multi_pic_type);
                    break;
                case 5://视频
                    typeView.setImageResource(R.drawable.icon_video_type);
                    break;
            }

        }


        private int dp2px(float dpValue){
            final float scale = mContext.getResources().getDisplayMetrics().density;
            return (int) (dpValue * scale + 0.5f);
        }


        public void setEditMode(boolean isEdit){
            this.isEditable = isEdit;
            notifyDataSetChanged();
        }

    }
}
